/**
 * 
 */
package com.moji.cyg.web.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.moji.cyg.web.extend.session.SessionUtil;
import com.moji.cyg.web.member.User4SessionInfo;
import com.moji.cyg.web.model.CygWebConstant;

/**
 * 类LoginInterceptor.java的实现描述：TODO 类实现描述
 * 
 * @author shengli.caosl 2012-3-5 下午9:35:48
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User4SessionInfo userInfo = SessionUtil.getSession(request, CygWebConstant.SESSION_USER_KEY,
                                                           User4SessionInfo.class);
        // 已经登录的用户，直接跳转
        if (userInfo != null && userInfo.isEffective()) {
            return true;
        }
        StringBuffer sb = request.getRequestURL();
        String queryStr = request.getQueryString();
        if (StringUtils.isNotEmpty(queryStr)) {
            sb.append(queryStr);
        }
        String url = sb.toString();
        String redirectUrl = CygWebConstant.PAGE_LOGIN;
        if (StringUtils.isNotEmpty(url)) {
            redirectUrl = CygWebConstant.PAGE_LOGIN + "?rUrl=" + URLEncoder.encode(url, CygWebConstant.CHAR_ENCODING);
        }
        response.sendRedirect(redirectUrl);
        return false;
    }
}
